package com.fubowen.reader.db.model

import android.view.View
import com.fubowen.reader.adapter.ISimple
import com.fubowen.reader.databinding.FragmentReaderBookshelfItemBinding
import com.fubowen.reader.db.bean.BookBean
import com.fubowen.reader.extension.toTimeString

class Bookshelf(var book: BookBean) : ISimple<Bookshelf> {
    override fun isSame(new: Bookshelf) = book.url == new.book.url

    override fun isSameOfContent(new: Bookshelf) = book == new.book

    override fun onBind(view: View, id: Int) {
        val binding = FragmentReaderBookshelfItemBinding.bind(view)
        binding.bookshelfName.text = book.name
        binding.bookshelfProgress.text = createProgress(book)
        binding.bookshelfDescription.text = createDescription(book)
        binding.bookshelfTag.text = createTag(book)
    }

    private fun createProgress(book: BookBean): String {
        if (book.readingChapter == 0) {
            return "未读过 · 共${book.chapterCount}章"
        }
        if (book.readingChapter == book.chapterCount) {
            return "已读到最新章 · 共${book.chapterCount}章"
        }
        return "${book.readingChapter}章/${book.chapterCount}章"
    }

    private fun createDescription(book: BookBean): String {
        return when (book.type) {
            BookBean.TYPE_LOCAL -> if (book.readingChapter != 0) "正在阅读 · 第${book.readingChapter}章 ${book.readingChapterName}" else ""
            BookBean.TYPE_WEB -> "${book.lastUpdateTime.toTimeString()}前更新 · 第${book.lastUpdateChapter}章 ${book.lastUpdateChapterName}"
            BookBean.TYPE_FINISH -> "已完结 · 共${book.chapterCount}章"
            else -> ""
        }
    }

    private fun createTag(book: BookBean): String {
        return when (book.type) {
            BookBean.TYPE_LOCAL -> "本地"
            BookBean.TYPE_WEB -> "连载"
            BookBean.TYPE_FINISH -> "完结"
            else -> ""
        }
    }
}

fun List<BookBean>.toBookshelf() = this.map { Bookshelf(it) }